<template>
  <div
    class="
            max-w-screen-xl
            mx-auto
            bg-white
            p-8
            rounded-lg
            shadow-2xl"
  >
    <h2 class="text-3xl my-6">评论</h2>
    <CommentBox @submit="addNewComment" />
    <DividerHorizontal />
    <!-- 回复容器 -->
    <div
      v-for="(comment) in comments"
      :key="comment.id"
    >
      <CommentItem
        :user="comment.user"
        :avatar="comment.avatar"
        :time="comment.time"
        :content="comment.content"
      />
      <ReplyContainer v-if="comment.replies">
        <CommentItem
          v-for="(reply) in comment.replies"
          :key="reply.id"
          :user="reply.user"
          :avatar="reply.avatar"
          :time="reply.time"
          :content="reply.content"
        />
      </ReplyContainer>
      <ReplyBox @submit="addNewComment($event, comment.id)" />
    </div>
  </div>
</template>

<script setup>
import CommentBox from './components/CommentBox.vue'
import DividerHorizontal from './components/DividerHorizontal.vue'
import CommentItem from './components/CommentItem.vue'
import ReplyBox from './components/ReplyBox.vue'
import ReplyContainer from './components/ReplyContainer.vue'
import face1 from './assets/images/x2.jpg'
import face2 from './assets/images/x3.jpg'
import face3 from './assets/images/x4.jpg'
import face4 from './assets/images/x5.jpg'

import {ref,onMounted} from 'vue'
onMounted(() => {
  getAllComments();
});
const comments = ref([
]);
async function getAllComments() {
  const res = await fetch("/api/comments");
  comments.value = await res.json();
}
const addNewComment = async (content, replyTo) => {
 let res=  await fetch(`/api/comments`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      content,
      ...(replyTo && { replyTo }),
    }),
  });
  console.log(res);
//  const newComment = await res.json();
//   if (!replyTo) {
//     comments.value.unshift(newComment);
//   } else {
//     comments.value.find((c) => c.id === replyTo).replies.unshift(newComment);
//   }
  // 新增完评论后，自动获取新的评论列表
  // Notion API 有延迟，在添加完 page 之后，需要过一会才能获取到新的评论列表
  setTimeout(async () => {
    await getAllComments();
  }, 1000);
};
const addNewReply = (reply,id)=>{
    const newReply = constructNewComment(reply)
    const comment = comments.value.find((comment)=>comment.id===id)
    if(comment.replies){
        comment.replies.push(newReply)
    }else{
        comment.replies = [newReply]
    }
}
</script>

<style lang="scss" scoped>

</style>